<template>
  <admin-container>
    <!--按钮组-->
    <!-- <div class="button-group">
      <el-button type="primary" @click="addProduct" size="small" icon="el-icon-plus">添加产品</el-button>
    </div> -->
    <!-- 筛选条件 -->
    <el-form :inline="true" size="small" :model="searchForm" class="search-form">
      <el-form-item label="产品分类">
        <el-select style="width: 150px;" v-model="searchForm.categoryId" placeholder="请选择">
          <el-option :value="0" :label="'全部'"></el-option>
          <el-option v-for="item in categorys" :key="item.id" :value="item.id" :label="item.categoryName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关键字">
        <el-input v-model="searchForm.keyword" placeholder="产品标题搜索" style="width: 250px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :table-header-props="{ disabled: true }" :data="tableData" border size="small" style="width: 100%">
      <el-table-column align="center" width="90px">
        <template slot="header" slot-scope="scope">
          <el-button type="text" @click="addProduct" size="small">
            <b>
              <i class="fa fa-plus"></i> 添加
            </b>
          </el-button>
        </template>
        <template slot-scope="scope">
          <el-button type="text" class="danger operate" @click="handleDelete(scope.row)">
            <i class="fa fa-remove"></i> 删除
          </el-button>
          <el-button v-if="!scope.row.publish" class="operate" type="text" @click="changePublish(scope.row, true)">
            <i class="fa fa-level-up"></i> 上架
          </el-button>
          <el-button v-else type="text" @click="changePublish(scope.row, false)" class="operate ignore">
            <i class="fa fa-level-down"></i> 下架
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="主图" align="center" width="100px">
        <template slot-scope="scope">
          <el-image class="productImage" :src="scope.row.mainImageUrl">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="名称 / Name">
        <template slot-scope="scope">
          <div class="ellipsis">
            <router-link :to="{ path: '/management/product/form', query: { id: scope.row.id } }">
              <b class="name">
                <div><i class="fa fa-edit edit"></i> {{ scope.row.productName }}</div>
                <div class="name-en">{{ scope.row.productNameEn }}</div>
              </b>
            </router-link>
            <div class="id">产品编号：{{ (scope.row.productID != null && scope.row.productID != '' ? scope.row.productID : "-")
            }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" width="150px">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.categoryId | categoryIdFilter(categorys) }}</el-tag>
          <div class="showPrice">
            <label>首页展示</label>
            <el-switch @change="changeDisplay(scope.row)" v-model="scope.row.homeShow"></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="right" label="零售价" width="200">
        <template slot-scope="scope">
          <div class="price">
            <template v-if="scope.row.currenciesData != nulll">
              {{ scope.row.currenciesData.unit }}
            </template>
            {{ scope.row.price.toFixed(2) | thousandSeparator }}
          </div>
          <div class="unit">
            <i :class="['fa', scope.row.showPrice ? 'fa-eye eye-display' : 'fa-eye-slash']"></i>
            <span v-if="scope.row.unit != null && scope.row.unit != ''">
              {{ scope.row.unit }} / {{ scope.row.unitEn }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="日期" align="center" width="150px">
        <template slot-scope="scope">
          <div class="date">
            <div>更新 {{ scope.row.updateDate }}</div>
            <div>创建 {{ scope.row.createDate }}</div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-tool">
      <el-pagination background layout="prev, pager, next" :page-size="searchForm.pageSize"
        :current-page="searchForm.pageIndex" :total="searchForm.pageTotal" @current-change="changePageIndex">
      </el-pagination>
    </div>
  </admin-container>
</template>

<script>
import AdminContainer from '@/components/Admin/AdminContainer.vue';
import * as productApi from '@/api/admin/productApi'
import * as productCategorieApi from '@/api/admin/productCategorieApi'

export default {
  components: {
    AdminContainer
  },
  data () {
    return {
      searchForm: {
        categoryId: 0,
        keyword: "",
        pageIndex: 0,
        pageSize: 20,
        pageTotal: 0
      },
      tableData: [],
      categorys: []
    }
  },
  methods: {
    addProduct () {
      var self = this;
      self.$router.push({
        path: '/management/product/form',
      })
    },
    editProduct (id) {
      var self = this;
      self.$router.push({
        path: '/management/product/form',
        query: {
          id: id,
        }
      })
    },
    handleSearch () {
      this.getProductList();
    },
    handleDelete (row) {
      // 删除文章
      var self = this;
      self.$confirm(`是否确定删除产品：“${row.productName}”?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        productApi.deleteProductById(row.id)
          .then(res => {
            if (res.code == 200) {
              self.$message({
                message: '删除成功！',
                type: 'success'
              });
              self.getProductList()
            }
            else if (res.code == 500) {
              self.$message.error(res.exception);
            }
          })
          .catch(err => {
            self.$message.error('接口发生错误');
          });
      });
    },
    getProductList () {
      var self = this;
      productApi.getAllProduct(self.searchForm.pageIndex, self.searchForm.pageSize, self.searchForm.categoryId, self.searchForm.keyword)
        .then(res => {
          if (res.code == 200) {
            self.tableData = res.data.data;
            self.searchForm.pageIndex = res.data.pageIndex;
            self.searchForm.pageSize = res.data.pageSize;
            self.searchForm.pageTotal = res.data.toalNumber;
          }
        })
    },
    changePageIndex (num) {
      var self = this;
      self.searchForm.pageIndex = num;
      self.getArticleList();
    },
    changePublish (row, status) {
      var self = this;
      var isChange = new Promise((resolve, reject) => {
        if (status == false) {
          self.$confirm(`是否确定下架产品：“${row.productName}”?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              resolve();
            })
            .catch(() => {
              reject();
            });
        }
        else {
          resolve();
        }
      });
      isChange
        .then(() => {
          row.publish = status;
          productApi.changePublish(row.id, row.publish)
            .then(res => {
              if (res.code == 200) {
                self.$message({
                  message: status ? '产品上架成功！' : '产品下架成功！',
                  type: 'success'
                });
                self.getProductList();
              }
              else if (res.code == 500) {
                self.$message.error(res.exception);
              }
            })
            .catch(err => {
              self.$message.error('接口发生错误');
            });
        })
    },
    getAllProductCategor () {
      var self = this;
      productCategorieApi.getAllProductCategories()
        .then(res => {
          if (res.code == 200) {
            self.categorys = res.data;
          }
          else if (res.code == 500) {
            self.$message.error(res.exception);
          }
        })
        .catch(err => {
          self.$message.error('保存失败，接口出错');
        })
    },
    tableRowClassName ({ row, rowIndex }) {
      if (row.homeShow) {
        return 'home-show';
      }
    },
    changeDisplay (row) {
      productApi.changeHomeShow(row.id, row.homeShow)
        .then(res => {
          if (res.code == 200) {
            this.$message({
              message: "保存成功",
              type: 'success'
            });
          }
          else if (res.code == 500) {
            this.$message.error(res.exception);
          }
        })
        .catch(err => {
          this.$message.error('接口发生错误');
        });
    }
  },
  filters: {
    categoryIdFilter: function (value, categorys) {
      const category = categorys.find(c => c.id === value);
      return category ? category.categoryName : '';
    },
    thousandSeparator (value) {
      if (!value) return ''
      return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
  },
  mounted () {
    var self = this;
    self.getProductList();
    self.getAllProductCategor();
  }
}
</script>

<style scoped>
.button-group {
  margin-bottom: 10px;
  border-bottom: 1px solid #F2F6FC;
  padding-bottom: 10px;
}

.page-tool {
  margin-top: 20px;
}

.eye-display {
  color: #409EFF;
}

.danger {
  color: #F56C6C;
}

.el-button+.el-button {
  margin-left: 1px;
}

.productImage {
  width: 48px;
  height: 48px;
}

.el-tag {
  width: 100%;
}

a {
  text-decoration: none;
  color: #606266;
}

a:hover {
  color: #409EFF;
}

.id {
  color: #909399;
  margin-left: 18px;
}

.name {
  font-size: 14px;
}

.edit {
  color: #409EFF;
}

.name-en {
  margin-left: 18px;
  font-size: 13px;
  font-weight: 500;
}

.date {
  line-height: 28px;
}

.operate {
  padding: 5px 0px;
}

.ignore {
  color: #909399;
}

.showPrice {
  margin-top: 10px;
}

.price {
  font-weight: bold;
  font-size: 13px;
}

.unit {
  /* color: #909399; */
}

.productImage>>>.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 14px;
}
</style>